package com.imooc.sm.global;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;

        String path = httpRequest.getServletPath();
        if(path.toLowerCase().indexOf("login") != -1){
            chain.doFilter(httpRequest, httpResponse);
        }else{
            Object obj = httpRequest.getSession().getAttribute("USER");
            if(obj != null){
                chain.doFilter(httpRequest, httpResponse);
            }else {
                httpResponse.sendRedirect(((HttpServletRequest) request).getContextPath() + "/toLogin.do");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
